package net.zjitc.login.servlet;

import net.zjitc.login.dao.UserDao;
import net.zjitc.login.dao.UserDaoImpl;
import net.zjitc.login.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/29 8:45
 * 继承、重写2个回方法、注解
 **/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 1、设置post请求编码（解决中文乱码问题）
        *  2、获取请求参数（用户输入的内容）
        *  3、若需要，将参数封装成对象
        *  4、调用dao层的方法完成登录功能（查询操作）
        *  5、根据dao层方法的返回值
        *     若不为空，表示用户名密码正确，将用户名保存在域对象，转发到succServlet
        *     若为空，表示用户名或密码错误，转发到failServlet
        *  */
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        UserDao dao=new UserDaoImpl();
        User login = dao.login(name, password);
        if(login!=null){
            /* 登录成功：
            *  1）把用户名保存在域对象
            *  2）转发到succServlet*/
            req.setAttribute("user",login.getName());
            req.getRequestDispatcher("/successServlet").forward(req,resp);

        }else{
           /*用户名或密码错误，登录失败:
           * 1)错误信息保存域对象
           * 2）转发到failServlet*/
            req.setAttribute("login_error","用户名或密码错误");
            req.getRequestDispatcher("/failServlet").forward(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
